﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectEuler
{
    class Problem4
    {
        public int Solve()
        {
            // max: 998001
            // 
            // 999-100

            for (int i = 999 * 999; i > 0; i--)
            {
                if (IsPalindrome(i) && IsFactorizableByTripleDigits(i)) return i;
            }
            return 0;
        }

        public bool IsPalindrome(int number)
        {
            var numberArray = number.ToString().ToArray();
            return IsPalindrome(numberArray);
        }

        public bool IsPalindrome(char[] numberArray)
        {
            if (numberArray.Count() < 2) return true;
            if (numberArray[0] == numberArray[numberArray.Count() - 1])
            {
                if (numberArray.Count() == 2) return true;
                var newNumberArray = new Char[numberArray.Count() - 2];
                for (int i = 0; i < numberArray.Count() - 2; i++)
                    newNumberArray[i] = numberArray[i+1];

                return IsPalindrome(newNumberArray);
            }
 
            return false;           
        }

        public bool IsFactorizableByTripleDigits(int number)
        {
            for (int i = 100; i < 1000; i++)
            {
                if (number % i == 0
                    && NumDigits(number / i) == 3)
                    return true;
            }
            return false;
        }

        public int NumDigits(int number)
        {
            return number.ToString().Count();
        }
    }
}
